<template>
	<view class="main-content">
		<view class="main-body" v-if="tabValue == 0">
			<view class="mt-20 block-top">
			  <view class="msg">
				<u-avatar
					v-if="user.lala"
					:src="user.lala"
					shape="circle"
					size="45"
					bgColor="#0087FC">
				</u-avatar>
				<u-avatar
					v-else
					:text="user.userName ? user.userName.slice(1) :''"
					:fontSize="user.userName && user.userName.length > 2?15:20"
					shape="circle"
					size="45"
					bgColor="#0087FC">
				</u-avatar>
			    <view class="msg-body">
			      <view class="msg-body__header">
			        <view>{{ user.userName }}</view>
			      </view>
			      <view class="msg-body__content">
					<text class="msg-body__content_userText">{{ user.dept.deptName }}</text> 
				  </view>
			    </view>
			  </view>
			  <view class="msg-body__right">
			  	<view class="msg-body__header">
			  	  <view>{{ user.courseName }}</view>
			  	</view>
			  </view>
			</view>
			
			<view class="icon-dk mt-20">
			  <view class="icon-list">
			  	<view class="icon-item">
			  	  <view class="msg-title">考勤{{ beginWorkTime }}</view>	
					<view class="msg-body__content_text" v-show="!isBeginDk">未打卡</view>
					<view class="msg-body__content" v-show="isBeginDk">
						<u-icon name="checkmark-circle-fill" color="#2979ff" customStyle="font-size:36rpx;line-height:36rpx;"></u-icon>
						<text class="msg-body__content_text">{{ beginDkTime }}已打卡</text> 
					</view>
			  	</view>
			  </view>
			  <!-- 打卡圆圈 -->
			  <view class="circle" 
			  @click="punchIn"
			  >
				  <view class="circle-body" :style="!inRange?'background-color: #01CB8B':''">
					  <view class="circle-body-title">签到打卡</view>
					  <view class="circle-body__content">{{nowTime}}</view>
				  </view>
			  </view>
			  <!-- 未在打卡区域提示 -->
			  <view v-if="!inRange" style="justify-content: center;display: flex;color: rgba(39, 40, 50, 0.6);margin-top: 40rpx;align-items: center;">
				<icon type="warn" size="16"/>
				<text class="circle-content">未进入考勤范围</text>
			  </view>
			  <view v-if="inRange" style="justify-content: center;display: flex;color: rgba(39, 40, 50, 0.6);margin-top: 40rpx;align-items: center;">
				<icon type="success" size="16"/>
				<text class="circle-content">已进入考勤范围：xxxx教学楼</text>
			  </view>
			</view>
		</view>
		
		<!-- <view  v-else-if="tabValue == 1">
			<kqtj ref="kqtj"></kqtj>
		</view> -->
		
		<u-tabbar
			:value="tabValue"
			:fixed="true"
			:placeholder="false"
			:safeAreaInsetBottom="false"
		>
			<u-tabbar-item text="打卡" icon="map" @click="clickTab(0)" ></u-tabbar-item>
			<!-- <u-tabbar-item text="统计" icon="file-text" @click="clickTab(1)" ></u-tabbar-item> -->
		</u-tabbar>
		
		<u-toast ref="uToast"></u-toast>
		
		<!-- 弹出层：提示打卡成功 -->
		<clock-success
		:showDkSuc="showDkSuc"
		:beginDkTime="beginDkTime"
		:courseName="courseName"
		:isBeginDk="isBeginDk"
		v-on:isShow='isShowSuc'
		></clock-success>
		
		<!-- 停留时间过久提示框 -->
		<view >
			<u-modal :show="showCloseTime" :confirmText='confirmText' @confirm="closeTimeOut">
				<view class="slot-content">
					<u-icon name="error-circle-fill" color="#f9ae3d" size="28"></u-icon>
					<rich-text class="slot-content__text" :nodes="content"></rich-text>
				</view>
			</u-modal>
		</view>
	</view>
</template>

<script>
	import kqtj from './kqtj.vue'
	import env from '@/env.js'
	import amap from '@/static/js/amap-wx.130.js';
	import { editDk, getDkInfo, changeStuInfo } from '@/api/kqdk.js'
	import getDateTime from '@/utils/getdateTime.js'
	import { strFormatHourMSTime } from '@/utils/format.js'
	import clockSuccess from '@/components/clock-success/clock-success.vue'
	import { getDistance, compareTime } from '@/utils/dkTools.js' //一些些工具
	import gcoord from 'gcoord';
	export default {
		components:{ kqtj, clockSuccess },
		data() {
			return {
				bssid: '',
				tabValue: 0,
				user: {
					userName:'松村触怒',
					courseName:'线性代数',
					dept:{
						deptName:'软件工程'
					}
				},
				nowTime: '',
				timeout: undefined,
				inRange: false, //是否在打卡区域范围
				amapPlugin: null,
				gaodekey: env.gaodekey,
				urlStr: '',
				distance: 99999,  //距离
				todayDate: '',  //当天日期
				isBeginDk: false,  //早上是否打卡
				dkInfo: '',  //打卡信息
				dkInfoId: '',  //打卡id
				showDkSuc: false,  //打卡是否成功(弹出成功弹框)
				beginDkTime: '', //打卡上班时间
				beginWorkTime: '',  //上班时间
				isDuanqi: false,  //是否在15s内
				content: '打卡停留时间过长',
				showCloseTime: false,
				confirmText: '我知道了',
				leaveTime:0,
				stayDuration:0,
			}
		},
		// onLoad() {
		// 	if (this.hasLogin) {
		// 	  this.user = uni.getStorageSync("user")
		// 	}
		// 	this.startInterval()
		// },
		onLoad() {
			this.amapPlugin = new amap.AMapWX({
				key: this.gaodekey
			});
			var timeStr = getDateTime.dateTimeStr('y-m-d');
			this.todayDate = timeStr 
		},
		onShow() {
			console.log('生么东西啊：');
			this.user = uni.getStorageSync("loginInfo").user
			console.log('this.user', this.user)
			// #ifdef MP-WEIXIN
			this.getSettingMess()
			// #endif
			let time = setTimeout(item => {
				this.showCloseTime = true
				clearTimeout(time)      
			}, 120000)
		},
		created(){
			this.getTodayDkInfo()
			// this.getPosition()
		},
		onHide() {
			this.closeInterval()
		},
		destroyed() {
			this.closeInterval()
		},
		methods: {
			// 获取当天打卡信息
			async getTodayDkInfo() {
				const { data } = await getDkInfo()
				if( data.code === 200 ) {
					if( data.data ) {
						this.dkInfo = data.data
						this.dkInfoId = this.dkInfo.id
						this.beginWorkTime = this.dkInfo.kqStartTime.slice(0,5)
						// this.endWorkTime = this.dkInfo.kqEndTime.slice(0,5)
						if( this.dkInfo.beginTime ) {
							this.isBeginDk = true
							this.beginDkTime = this.dkInfo.beginTime.slice(-8,-3)
							// this.isLate = this.dkInfo.late
						}
					}
				}
			}, 
			getSettingMess(){
				const _this = this;
				// 成功获取位置
				// 获取已授权类别
				uni.authorize({
					scope: 'scope.userLocation',
					// 成功
					success() {
						_this.startInterval()
					},
					// 失败
					fail() {
						// 1 用户拒绝授权
						// 2 用户之前拒绝了授权，此接口会直接进入失败回调
						//  以上两种情况都会进入到fail回调中
						// 一般搭配uni.getSetting和uni.openSetting使用

						// 官方文档中明确指出从2.3.0版本开始，当用户发生点击行为后才可以跳转打开设置页，不允许在用户无任何操作的情况下进行跳转
						// so报错 openSetting:fail can only be invoked by user TAP gesture.

						// 解决没办法 可通过提示框的按钮点击 触发opensetting
						//弹出框
						uni.showModal({
							title: '提示',
							content: '位置未授权，不可使用打卡功能，请重新授权定位权限',
							showCancel:true,
							success: function (res) {
								if(res.confirm){
									//打开设置
									uni.openSetting({
									  success(res) {
										let userLocation = res.authSetting['scope.userLocation'];
										if(userLocation){
											// 继续进行授权成功后的操作
											//用户开启位置权限
											uni.showToast({
												title: '定位已开启',
												duration: 2000
											});
										}else{
											// 用户拒接授权 给提示
											uni.showToast({
												title: '您已拒绝定位',
												duration: 2000,
												icon: "error"
											});
										}
									  }
									});
								}else{
									// 用户拒接授权 给提示
									uni.showToast({
										title: '您已拒绝定位',
										duration: 2000,
										icon: "error"
									});
									_this.distance = 99999
									if(Math.round(_this.distance) <= Number(_this.dkInfo.distance)){
									  _this.inRange = true
									}else {
									  _this.inRange = false
									}
								}
							}
						});
						
					}
				})
			},
			getWifi() {
				// 判断地址范围在多少之内可以
				const _this = this;
				// #ifdef MP-WEIXIN
				// 成功获取位置
				_this.amapPlugin.getRegeo({
					success: (data) => {
						// _this.address 可根据自己的实际情况修改
						_this.distance = getDistance(`${data[0].latitude}`, `${data[0].longitude}`,_this.dkInfo.latitude,_this.dkInfo.longitude)
						console.log('distance',_this.distance)
						if(_this.isBeginDk){
							if(Math.round(_this.distance) <= Number(_this.dkInfo.distance)){
								_this.inRange = true
								_this.startTimer();
							}else {
								_this.inRange = false
								_this.stopTimer();
							}
						}
					},
					// 获取位置失败
					fail: (err) => {
						uni.showToast({
							title: "获取位置失败",
							icon: "error"
						})
					}
				});
				// #endif
			},
			// 上下班打卡
			punchIn(){
				if(!this.inRange){
					this.$refs.uToast.show({
					  type: 'default',
					  message: '未进入打卡范围'
					})
					return
				}
				
				// 查询用户上班点
				let dateTime = this.todayDate + " " + this.nowTime
				this.editDkInfo(this.dkInfoId, dateTime)
			},
			// 上下班打卡
			async editDkInfo(id, sbDkTime){
				let commitContent = {id:id, beginTime:sbDkTime }
				// this.xiabanTime = strFormatHourMSTime(xbDkTime)
				const { data } = await editDk(commitContent)
				if(data.code === 200) {
					this.popupShow = false
					this.isBeginDk = true
					this.dkInfo.beginTime = sbDkTime
					this.beginDkTime = sbDkTime.slice(-8,-3)
					let time = setTimeout(item => {
						this.showDkSuc = true
						clearTimeout(time)      
					}, 500)
					this.startMP3()
				}
				this.closeDkSucAuto()
			},
			startMP3() {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = 'https://www.zxsl.zxmap.cn/zxch-app/2023/05/09/be646e18316f42548f1333bd058f03fd.mp3';
				innerAudioContext.onPlay(() => {console.log('成功播放')});
			},
			closeDkSucAuto(){
				//设置五秒后弹窗自动关闭
				let time = setTimeout(item => {
					this.showDkSuc = false;
					clearTimeout(time)      
				}, 3000)
			},
			isShowSuc(index){
				this.showDkSuc = index
			},
			clickTab(e) {
				if(e == 0 ){
					this.startInterval()
				}
				this.tabValue = e
			},
			//打开定时器
			startInterval() {
				var that = this
				this.timeout = setInterval(function () {
					var now = new Date();
					var hour = now.getHours();//得到小时
					var minu = now.getMinutes();//得到分钟
					var sec = now.getSeconds();//得到秒
					　var MS = now.getMilliseconds();//获取毫秒
					if (hour < 10) hour = "0" + hour;
					if (minu < 10) minu = "0" + minu;
					if (sec < 10) sec = "0" + sec;
					var time = "";
					that.nowTime = hour + ":" + minu + ":" + sec;
					 console.log('高德定位接口')
					that.getWifi()
				},3000);
			},
			//清空定时器，即停止定时器
			closeInterval() {
				clearInterval(this.timeout);
			},
			closeTimeOut() {
				this.showCloseTime = false
				clearInterval(this.timeout);
				uni.navigateBack()
			},
			changeStuStatus(time,duration){
				let commitContent = {id:id, status:'1', time: time,duration:duration}
				const { data } = changeStuInfo(commitContent)
				// if(time)
			},
			// 开始计时
			startTimer() {
			  this.timer = setInterval(() => {
				this.stayDuration++;
			  }, 1000);
			},
			// 停止计时
			stopTimer() {
			  clearInterval(this.timer);
			  this.timer = null;
			},
		}
	}
</script>

<style lang="scss">
@import "./index.scss";

.block-top{
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	width: 690rpx;
	box-sizing: border-box;
	background-color: #ffffff;
	border-radius: 10rpx;
	padding: 20rpx 0;
}

.msg-body__right{
	margin-right: 50rpx;
}

.circle{ 
	margin-top: 200rpx;
	// position: relative;
	&-body{
		width: 250rpx;
		height: 250rpx; 
		background-color: #0089FF;
		border-radius: 50%; 
		margin: auto;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		// padding:95rpx 0;
		// position: absolute;
		// top: 35%;
		// margin-left: 26%;
		text-align: center;
		// justify-content: center;
		&-title {
		  font-size: 35rpx;
		  // letter-spacing: 0rpx;
		  color: #ffffff;
		}
		&__content {
		  font-size: 28rpx;
		  color: #d6d6d6;
		}
	}
	&-content {
		font-size: 28rpx;
		margin-left: 6rpx;
	}
}

.slot-content {
	display: flex;
	align-items: center;
	flex: 1;
	justify-content: center;
	&__text {
		margin-left: 10rpx;
	}
}
</style>
